//弹出窗口定义
function _alert(title, fun) {
    var obj = $(".alertBox");

    obj.find(".text").html(title);
    if (typeof fun == "undefined") {
        obj.find(".button").click(function () {
            obj.hide();
        });
        obj.find(".button").show();
        obj.find(".buttonBox").hide();
    } else if (typeof fun == "string") {
        obj.find(".button").click(function () {
            window.location.href = fun;
        });
        obj.find(".button").show();
        obj.find(".buttonBox").hide();
    } else {
        obj.find(".button").hide();
        obj.find(".buttonBox").show();
        obj.find(".cancel").click(function () {
            obj.find(".confirm").unbind("click");
            obj.hide();
        });
        obj.find(".confirm").off("click");
        obj.find(".confirm").on("click", function () {
            obj.hide();
            return fun();
        });
    }
    obj.show();
}
/* *
 * 调用此方法发送HTTP请求。
 *
 * @public
 * @param   {string}    url           请求的URL地址
 * @param   {mix}       data          发送参数
 * @param   {Function}  callback      回调函数
 * @param   {string}    type          请求的方式，有"GET"和"POST"两种
 * @param   {boolean}   asyn          是否异步请求的方式,true：异步，false：同步,没有回调函数必须同步否则将发生错误
 * @param   {string}    dataType      响应类型，有"JSON"、"XML"和"TEXT"三种
 * iqgmy
 */
function jq_ajax(url, data, callback, type, async, dataType) {
    if (typeof callback != "undefined") async = true;
    type = type != "get" && type != "GET" ? "POST" : type;
    async = typeof async == "undefined" ? false : async;
    dataType = typeof dataType == "undefined" ? "json" : dataType;

    var jq_ajax_result = new Object();
    if (typeof data == "object") {
        var date_str = "";
        for (var key in data)
            date_str += key + "=" + encodeURIComponent(data[key]) + "&";
        data = date_str;
    }
    $.ajax({
        url: url,
        type: type,
        data: data,
        dataType: dataType,
         contentType: "application/json",
        headers: { token: $.cookie("code") },
        async: async,
        success: function (result) {
            if (result.errno == "401") {
				if (!authorize) {
					getweixinCode()
				} else {
					getLogin(authorize)
				}
				return 
			}
            jq_ajax_result = result;
            if (callback == "") return false;
            if (typeof callback == "function") return callback(result);
            if (typeof callback != "undefined")
                return eval(callback + "(result)");
        },
        error: function () {
            jq_ajax_result.code = 0;
            jq_ajax_result.msg = "网络异常，请重新尝试.";
            if (callback == "") return false;
            if (typeof callback == "function") return callback(jq_ajax_result);
            if (typeof callback != "undefined")
                return eval(callback + "(jq_ajax_result)");
        },
    });

    return jq_ajax_result;
}
var isContainer = false;
//侧滑显示
function container(obj) {
    //侧滑显示删除按钮
    var expansion = null; //是否存在展开的list
    var container = document.querySelectorAll(obj);
    for (var i = 0; i < container.length; i++) {
        var x, y, X, Y, swipeX, swipeY;
        container[i].addEventListener("touchstart", function (event) {
            x = event.changedTouches[0].pageX;
            y = event.changedTouches[0].pageY;
            swipeX = true;
            swipeY = true;
            if (expansion) {
                //判断是否展开，如果展开则收起
                expansion.className = "";
            }
        });
        container[i].addEventListener("touchmove", function (event) {
            isContainer = true;
            X = event.changedTouches[0].pageX;
            Y = event.changedTouches[0].pageY;
            // 左右滑动
            if (swipeX && Math.abs(X - x) - Math.abs(Y - y) > 0) {
                // 阻止事件冒泡
                event.stopPropagation();
                if (X - x > 1) {
                    //右滑
                    event.preventDefault();
                    this.className = ""; //右滑收起
                }
                if (x - X > 1) {
                    //左滑
                    event.preventDefault();
                    this.className = "swipeleft"; //左滑展开
                    expansion = this;
                }
                swipeY = false;
            }
            // 上下滑动
            if (swipeY && Math.abs(X - x) - Math.abs(Y - y) < 0) {
                swipeX = false;
            }
        });
    }
}
//整合表单数组
$.fn.toJson = function () {
    var arrayValue = $(this).serializeArray();
    var json = {};
    $.each(arrayValue, function () {
        var item = this;
        if (json[item["name"]]) {
            json[item["name"]] += "," + item["value"];
        } else {
            json[item["name"]] = item["value"];
        }
    });
    return json;
};
//计数函数
var countTxtSw = false;
var countTxtStatus = true;
function countTxtEvent(_txt, _txtNum, length) {
    var txt = document.getElementById(_txt);
    var txtNum = document.getElementById(_txtNum);

    txt.addEventListener("keyup", function () {
        if (countTxtSw == false) {
            countTxt(txt, txtNum, length);
        }
    });
    txt.addEventListener("compositionstart", function () {
        countTxtSw = true;
    });
    txt.addEventListener("compositionend", function () {
        countTxtSw = false;
        countTxt(txt, txtNum, length);
    });
}
function countTxt(txt, txtNum, length) {
    if (countTxtSw == false && txt.value.length <= length) {
        //只有开关关闭时，才赋值
        txtNum.textContent = txt.value.length + "/" + length;
    } else {
        countTxtStatus = false;
        txtNum.textContent = length + "/" + length;
        txtNum.style.color = "#f65236";
    }
}

//判断是否存在画布
function isCanvasSupported() {
    var elem = document.createElement("canvas");
    return !!(elem.getContext && elem.getContext("2d"));
}

//压缩方法
function compress(event, callback) {
    if (typeof FileReader === "undefined") {
        console.log("当前浏览器内核不支持base64图标压缩");
        //调用上传方式  不压缩
    } else {
        try {
            var file = event.currentTarget.files[0];
            var file_type = file.type;
            if (!/image\/\w+/.test(file.type)) {
                file_type = "image/jpg";
            }

            var reader = new FileReader();
            reader.onload = function (e) {
                var image = $("<img/>");
                image.load(function () {
                    console.log("开始压缩");
                    var canvas = document.createElement("canvas");
                    var width = this.width;
                    var height = this.height;

                    //如果图片大于80万像素，计算压缩比并将大小压至80万以下
                    var ratio;
                    if ((ratio = (width * height) / 800000) > 1) {
                        ratio = Math.sqrt(ratio);
                        width /= ratio;
                        height /= ratio;
                    }
                    canvas.width = width;
                    canvas.height = height;

                    var context = canvas.getContext("2d");
                    context.clearRect(0, 0, width, height);
                    context.drawImage(this, 0, 0, width, height);
                    var data = canvas.toDataURL(file_type);
                    //压缩完成执行回调
                    callback(data);
                });
                image.attr("src", e.target.result);
            };
            reader.readAsDataURL(file);
        } catch (e) {
            console.log("压缩失败!");
            //调用上传方式  不压缩
        }
    }
}
check()
//判断是否需要微信授权登录
function check() {
    // todo: 开发
    // return;

    var token =  $.cookie("code");
    console.log(typeof token)
    var promoterId = getUrlParam('promoterId')?getUrlParam('promoterId'):getUrlParam('PID')?getUrlParam('PID'):null
    if ( token == 'null' ||!token) {
        
        if(promoterId == null){
            window.location.href = '/authorize.html'
        }else{
           window.location.href = '/authorize.html?promoterId='+promoterId 
        }
       
    }
    
}

function getUrlParam(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
            var r = window.location.search.substr(1).match(reg);  //匹配目标参数
            if (r != null) return unescape(r[2]); return null; //返回参数值
        }
//弹出提示
function _toast(text, time) {
    var time = time || 1500;
    $("body").append(
        '<div class="ZP-toast" ><div style="top:50%">' + text + "</div></div>"
    );
    setTimeout(function () {
        $(".ZP-toast").remove();
    }, time);
}



//微信分享朋友圈
function weixinShare(data,infor){
    
  
	     	wx.config({
		      debug: false,
		      appId: data.appId,
		      timestamp:data.timestamp,
		      nonceStr:data.nonceStr,
		      signature:data.signature,
			  jsApiList: [
			      'checkJsApi',
		          'onMenuShareTimeline',
		          'onMenuShareAppMessage',
                'showOptionMenu'
		      ]
		  });
	     	
	      wx.ready(function(){
			 //wx.showOptionMenu();/***隐藏分享菜单****/ 
			 wx.checkJsApi({
		      jsApiList: [
		        'getLocation',
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'showOptionMenu'
		      ],
		      success: function (res) {
		        //alert(res.errMsg);
		      }
		    });
			 wx.showOptionMenu()
			wx.onMenuShareAppMessage({
			      title: infor.title,
			      link: infor.link,
			      desc: infor.desc,
			      imgUrl: infor.imgUrl,
			      trigger: function (res) {
			     //   alert('用户点击发送给朋友');
			      },
			      success: function (res) {
			     //   alert('用户点击发送给朋友');
			      },
			      cancel: function (res) {
			        //alert('已取消');
			      },
			      fail: function (res) {
			        alert(res.errMsg);
			      }
			   });
			
			  // 2.2 监听“分享到朋友圈”按钮点击、自定义分享内容及分享结果接口
			  wx.onMenuShareTimeline({
			     title: infor.title,
			      link: infor.link,
			      desc: infor.desc,
			      imgUrl: infor.imgUrl,
			      trigger: function (res) {
			        //alert('用户点击分享到朋友圈');
			      },
			      success: function (res) {
			        
			      },
			      cancel: function (res) {
			        //alert('已取消');
			      },
			      fail: function (res) {
			        alert(res.errMsg);
			      }
			});
			
			
			 
		         wx.error(function(res){
            // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
            console.log("errorMSG:"+res);
});
	       });	
		
}


